//
//  TKIMHttpRequestHelper.m
//  TKIM
//
//  Created by macpro on 15/12/2.
//  Copyright © 2015年 liupm. All rights reserved.
//

#import "TKIMHttpRequestHelper.h"

@interface TKIMHttpRequestHelper ()<NSURLConnectionDataDelegate,NSURLConnectionDelegate>
{
    //请求数据的地址
    NSURL *_url;
    //文件大小
    long long _allFileSize;
    HttpRequestReceiveProgessBlock _reqeustProgessBlock;
    HttpRequestDidFinishBlock _requestFinishBlock;
    HttpRequestDidErrorBlock _requestErrorBlock;
}

/**
 *  保存下载的数据
 */
@property (nonatomic, strong) NSMutableData *downalodData;

@end

@implementation TKIMHttpRequestHelper

/**
 *  构造方法
 *
 *  @param url 要请求的远程地址
 */
- (instancetype)initWithUrl:(NSURL *)url
{
    if (self = [super init])
    {
        _url = url;
    }
    return self;
}

/**
 *  getter方法
 */
- (NSMutableData *)downalodData
{
    if (!_downalodData)
    {
        _downalodData = [[NSMutableData alloc] init];
    }
    return _downalodData;
}

/**
 *  请求数据（发送异步请求）
 */
- (void)startHttpRequest
{
    //1.判断地址是否为空
    if (!_url)  return;
    //2.发送异步请求
    NSURLRequest *request = [NSURLRequest requestWithURL:_url];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
}

#pragma mark - setter方法
/**
 *  设置成功和失败的回调
 */
- (void)setHttpRequestDidFininshBlock:(HttpRequestDidFinishBlock)finishBlock requestDidErrorBlock:(HttpRequestDidErrorBlock)errorBlock
{
    _requestFinishBlock = finishBlock;
    _requestErrorBlock = errorBlock;
}

/**
 *  设置进度回调
 */
- (void)setHttpRequestReceiveProgessBlock:(HttpRequestReceiveProgessBlock)progessBlock
{
    _reqeustProgessBlock = progessBlock;
}

#pragma mark - NSURLConnectionDelegate
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    //1.清空数据
    self.downalodData.length = 0;
    //2.获取数据总大小
    _allFileSize = [response expectedContentLength];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [self.downalodData appendData:data];
    CGFloat progess = (CGFloat)self.downalodData.length / _allFileSize;
    //3.进度的回调
    if (_reqeustProgessBlock)
    {
        _reqeustProgessBlock(progess);
    }
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    self.responseData = self.downalodData;
    self.responseString = [[NSString alloc] initWithData:self.downalodData encoding:NSUTF8StringEncoding];
    //成功回调
    if (_requestFinishBlock)
    {
        _requestFinishBlock(self);
    }
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //失败回调
    if (_requestErrorBlock)
    {
        _requestErrorBlock(error);
    }
}

@end
